package jsyf.oa.service.wechat.service_account;


import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.dao.wechat.service_account.WeChatUserDao;
import jsyf.oa.entity.wechat.service_account.WeChatUserEntity;
import jsyf.oa.facade.wechat.config.WeChatConst;
import jsyf.oa.facade.wechat.service_account.WechatUserFacade;
import jsyf.oa.facade.wechat.service_company.TokenFacade;
import jsyf.oa.service.wechat.service_company.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class WeChatUserService implements WechatUserFacade {

    @Autowired
    private WeChatUserDao weChatUserDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private TokenFacade tokenFacade;

    @Override
    public String saveUserByeventKey(String openId, String eventKey) {

        String accessToken = tokenFacade.getServiceAccessToken(WeChatConst.weChat_account_type);
        // 拼装url
        String url = WeChatConst.get_user_info.replace("ACCESS_TOKEN",accessToken);
        url = url.replace("OPENID",openId);
        // 调用接口
        JSONObject jsonObject = HttpUtil.request(url, "GET", openId);
        WeChatUserEntity entity = JSON.toJavaObject(jsonObject, WeChatUserEntity.class);

        if (entity.getSubscribe_time() != null){
            long subscribeTime = Long.parseLong(entity.getSubscribe_time()) * 1000;
            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(subscribeTime);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
            String dataTime = dateFormat.format(cal.getTime());
            entity.setSubscribe_time(dataTime);
        }

        JSONObject telJsonObject = (JSONObject) JSONObject.parse(eventKey);
        String customerTel = telJsonObject.getString("customerTel");
        String salerId = telJsonObject.getString("salerId");
        entity.setCustomerTel(customerTel);
        entity.setSalerId(salerId);
        Integer rows = null;
        if (jsonObject!=null) {
            if (jsonObject.containsKey("errcode")) {
                rows = 0;
            }else {
                rows = weChatUserDao.add(entity);
            }
        }
        return rows == 0 ? "" : entity.getId();
    }

    @Override
    public int updateUserByOpenId(String openId, int status) {

        return weChatUserDao.updateByOpenId(openId, status);
    }

    @Override
    public int updateUserByCustomerTel(String openId, String phone) {

        return weChatUserDao.updateByCustomerTel(openId, phone);
    }

    @Override
    public int updateUserByEventKey(String openId, String eventKey) {

        return weChatUserDao.updateByEventKey(openId, eventKey);
    }

    @Override
    public JSONObject getOAUserByPhone(String phone) {

        List<JSONObject> jsonList = userDao.getJSONListByCondition(" and tel = ?",new Object[]{phone});
        if (jsonList != null && jsonList.size() > 0) {
            return jsonList.get(0);
        }
        return null;
    }

    @Override
    public String saveUserByOpenId(String openId) {

        String accessToken = tokenFacade.getServiceAccessToken(WeChatConst.weChat_account_type);
        // 拼装url
        String url = WeChatConst.get_user_info.replace("ACCESS_TOKEN",accessToken);
        url = url.replace("OPENID",openId);
        // 调用接口
        JSONObject jsonObject = HttpUtil.request(url, "GET", openId);
        WeChatUserEntity entity = JSON.toJavaObject(jsonObject, WeChatUserEntity.class);

        Integer rows = null;
        if (jsonObject!=null) {
            if (jsonObject.containsKey("errcode")) {
                rows = 0;
            }else {
                rows = weChatUserDao.add(entity);
            }
        }
        return rows == 0 ? "" : entity.getId();
    }

    @Override
    public boolean isExit(String openId) {

        return weChatUserDao.isExitByOpenId(openId);
    }

    @Override
    public boolean isExitByCustomerTel(String customerTel) {

        return weChatUserDao.isExitByCustomerTel(customerTel);
    }

    @Override
    public List<JSONObject> getAllUser() {

        List<JSONObject> list = weChatUserDao.getJSONListByCondition("", new Object[]{});
        return list;
    }

    @Override
    public JSONObject getUserByPage(JSONObject jsonParam, int requestPage, int pageSize) {

        String subscribe = jsonParam.getString("subscribe");
        String customerTel = jsonParam.getString("customerTel");
        String salerName = jsonParam.getString("salerName");
        String salerTel = jsonParam.getString("salerTel");

        //查询微信用户
        StringBuilder condition = new StringBuilder();
        List<Object> sqlArgs = new ArrayList<Object>();

        if (!StringUtils.isBlank(subscribe)) {
            condition.append(" and subscribe = ?");
            sqlArgs.add(subscribe);
        }
        if (!StringUtils.isBlank(customerTel)) {
            condition.append(" and customerTel LIKE ?");
            sqlArgs.add(customerTel+"%");
        }
        if (!StringUtils.isBlank(salerName)) {
            condition.append(" and salerName LIKE ?");
            sqlArgs.add(salerName+"%");
        }
        if (!StringUtils.isBlank(salerTel)) {
            condition.append(" and salerTel LIKE ?");
            sqlArgs.add(salerTel+"%");
        }
        List<JSONObject> listUser = weChatUserDao.getViewJSONListByPage(condition.toString(), sqlArgs.toArray(), requestPage, pageSize);
        //查询出总数
        int recordCount = weChatUserDao.getViewPageCount(condition.toString(), sqlArgs.toArray());
        int recordSize = Integer.valueOf(pageSize).intValue();
        int pageCount = 0;
        if (recordCount < recordSize) {
            pageCount = 1;
        } else {
            double flag = Math.ceil(recordCount / recordSize);
            pageCount = ((int) flag);
        }
        if (recordCount == 0) {
            pageCount = 0;
        }
        JSONObject obj_result = new JSONObject();
        JSONObject obj_sendData = new JSONObject();
        //子对象
        obj_sendData.put("recordCount", recordCount);
        obj_sendData.put("pageCount", pageCount);
        obj_sendData.put("requestPage", 1);
        obj_result.put("pager", obj_sendData);
        // 子数组对象
        obj_result.put("records", listUser);
        return obj_result;
    }
}